package com.srwl.mytx.domain;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.srwl.mytx.Helper;
import com.srwl.mytx.utils.FileUtils;
import com.srwl.mytx.utils.IDUtils;
import com.srwl.mytx.utils.IMFileTools;
import com.srwl.mytx.utils.IMImageUtils;
import com.srwl.mytx.utils.IMThumbnailUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

import top.zibin.luban.Luban;

public class FileUpLoad extends Thread {
    private static final String TAG = "FileUpLoad";
    private Context context;
    private List<MyFile> totalSelectFile;//总的选择图片文件集合，包括本地的和远程的（历史文件）
    private InteractionListener listener;
    private int widthPixels;
    private int heightPixels;
    private Handler mHandler = new Handler(Looper.getMainLooper());

    public FileUpLoad(Context context, List<MyFile> totalSelectFile, InteractionListener listener) {
        this.context = context;
        this.totalSelectFile = totalSelectFile;
        this.listener = listener;
    }


    /**
     * 根据文件类型的状态，
     * 远程文件和已经上传成功了的，直接跳过
     * 如果是本地视频，直接上传，因为在视频录制过程中已经确定了视频的大小，这儿无须压缩
     * 如果是本地图片，没有压缩过，就先压缩，再上传
     */
    public void run() {

        int noNeedUploadFileCount = 0;//可保存到服务端的文件数量：包括远程文件和已经上传成功的文件
        for (int i = 0; i < totalSelectFile.size(); i++) {
            MyFile myFile = totalSelectFile.get(i);
            //如果是远程文件，continue
            if (myFile.getStatus() == MyFile.FILE_STATUS_REMOTE) {
                noNeedUploadFileCount++;
                continue;
            }
            //如果已经上传成功的状态，continue
            if (myFile.getStatus() == MyFile.FILE_STATUS_UPLOAD_SUCCESS) {
                noNeedUploadFileCount++;
                continue;
            }
            int finalI = i;
            mHandler.post(() -> listener.onShowProgressBar("第 " + (finalI + 1) + " 个文件开始上传"));
            //如果是本地视频文件，上传，然后continue
            if (myFile.getType() == MyFile.FILE_TYPE_VIDEO) {

                if (!TextUtils.isEmpty(myFile.getVideoCover())) {
                    compressCoverPicture(myFile);
                    final String fileName = IMImageUtils.genImageName();
                    String coverName = "cover_" + fileName;
                    String videoCover = myFile.getVideoCover();
                    myFile.setVideoCover(coverName);//封面图片按默认上传成功处理，直接保存，或许后续所有文件都按这样的方式处理，只管调用上传，
                    AliOssService.getInstance().uploadTopicImage(coverName, videoCover, new AliOssService.OssListener() {
                        @Override
                        public void onProgressChange(int progress) {

                        }

                        @Override
                        public void onSuccess(String objectKey) {
                            Log.i(TAG, "onSuccess: 视频封面上传完成 objectKey：" + objectKey + "本地地址：" + videoCover);
                        }

                        @Override
                        public void onFailure(String errorCode, String message) {
                            Log.e(TAG, "onFailure: 视频封面上传失败了，，，" + message);
                        }
                    });
                }
                upLoadVideo(myFile, i);
                continue;
            }
            //能走到这儿的，都是本地图片，如果没有压缩，需要压缩图片

            if (!myFile.isCompress()) {

                if (widthPixels == 0) {
                    widthPixels = context.getResources().getDisplayMetrics().widthPixels;
                    float density = context.getResources().getDisplayMetrics().density;
                    heightPixels = (int) ((float) context.getResources().getDisplayMetrics().heightPixels - 32.0F * density);//高度是减去状态栏的高度
                }
                compressPicture(myFile);
            }
            uploadPicture(myFile, i);

        }
        //如果文件全部都是历史文件或者已经上传成功的文件，那就直接通知上传完成
        if (noNeedUploadFileCount == totalSelectFile.size()) {
            mHandler.post(() -> listener.onUploadComplete());

        }
    }

    /**
     * 对图片做压缩处理
     *
     * @param myFile
     */
    private void compressPicture(MyFile myFile) {
        String filePath = Helper.getInstance().getBasePath() + File.separator + IDUtils.genImageName();
        FileUtils.copyFile(context, myFile.getUri(), new File(filePath));
        try {
            File file = Luban.with(context).get(filePath);
            Log.i(TAG, "compressPicture: 压缩后大小：" + file.length() + "  文件地址：" + file.getPath());

            myFile.setUrl(file.getPath());//把压缩后的图片地址作为本地文件的地址
            myFile.setCompress(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void compressCoverPicture(MyFile myFile) {
        String videoCover = myFile.getVideoCover();
        if (TextUtils.isEmpty(videoCover)) {
            Log.e(TAG, "compressCoverPicture: 视频封面为空");
            return;
        }
        // String savePath = baseFilePath + File.separator + IDUtils.genImageName();
        //int ori = IMImageUtils.getOrientation(videoCover, context, (Uri) null);
        //压缩图片并保存到savePath，使用的阿里IM的压缩方案，github 上有开源的压缩方案，以后可以去看看，比较下
        // Bitmap bitmap = IMThumbnailUtils.compressFileAndRotateToBitmapThumb(videoCover, widthPixels, heightPixels, ori, savePath, true, false);
        // IMFileTools.deleteFile(savePath);
        // IMFileTools.writeBitmap(savePath, bitmap, 90);
        try {
            File file = Luban.with(context).get(videoCover);
            Log.i(TAG, "compressPicture: 压缩后大小：" + file.length() + "  文件地址：" + file.getPath());
            myFile.setVideoCover(file.getPath());//把压缩后的图片地址作为本地文件的地址
            myFile.setCompress(true);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void upLoadVideo(MyFile localVideoFile, int index) {
        // File file = new File(localVideoFile.getUrl());

        //根据当前时间点生成文件名字
        final String fileName = IMImageUtils.genImageName();
        localVideoFile.setId(fileName);
        Log.d(TAG, "upLoadVideo: " + localVideoFile.getUrl());

        AliOssService.getInstance().uploadTopicVideo(fileName, localVideoFile.getUrl(), new AliOssService.OssListener() {
            @Override
            public void onProgressChange(int progress) {

            }

            @Override
            public void onSuccess(String objectKey) {
                Log.d(TAG, "onUploadComplete: 第" + index + "视频上传完成");
                mHandler.post(() -> listener.onShowProgressBar("第 " + (index + 1) + " 个文件上传完成"));
                localVideoFile.setUrl(objectKey);
                localVideoFile.setStatus(MyFile.FILE_STATUS_UPLOAD_SUCCESS);
                checkUploadComplete();
            }

            @Override
            public void onFailure(String errorCode, String message) {

                Log.e(TAG, "onUploadFailed: 第 " + index + "视频上传失败：" + message);
                // mHandler.post(() -> listener.onShowProgressBar("第 " + (index + 1) + " 个文件上传失败"));
                localVideoFile.setStatus(MyFile.FILE_STATUS_UPLOAD_FAIL);
                checkUploadComplete();
            }
        });

    }


    private void uploadPicture(MyFile localPictureFile, int index) {

        //根据当前时间点生成图片名字
        final String fileName = IMImageUtils.genImageName();
        localPictureFile.setId(fileName);
        Log.i(TAG, "uploadPicture: " + localPictureFile.getUrl());
        AliOssService.getInstance().uploadTopicImage(fileName, localPictureFile.getUrl(), new AliOssService.OssListener() {
            @Override
            public void onProgressChange(int progress) {

            }

            @Override
            public void onSuccess(String objectKey) {
                Log.d("PublishTopicActivity", "图片 " + fileName + " 上传成功");
                Log.d(TAG, "onUploadComplete:第" + index + "图片上传完成");

                mHandler.post(() -> listener.onShowProgressBar("第 " + (index + 1) + " 个文件上传完成"));
                localPictureFile.setUrl(objectKey);
                localPictureFile.setStatus(MyFile.FILE_STATUS_UPLOAD_SUCCESS);
                checkUploadComplete();
            }

            @Override
            public void onFailure(String errorCode, String message) {
                Log.e(TAG, "onUploadFailed: 第" + index + "图片上传失败" + message);
                mHandler.post(() -> listener.onShowProgressBar("第 " + (index + 1) + " 个文件上传失败"));
                localPictureFile.setStatus(MyFile.FILE_STATUS_UPLOAD_FAIL);
                checkUploadComplete();
            }
        });
    }

    /**
     * 检查是否所以文件都上传完成，如果上传完成，就调用保存服务端的方法
     */
    private void checkUploadComplete() {
        int remoteFileCount = 0;
        int uploadSuccessCount = 0;
        for (MyFile myFile : totalSelectFile) {
            if (myFile.getStatus() == MyFile.FILE_STATUS_LOCAL) {//有文件还是本地状态，说明没有上传完成
                return;
            }

            if (myFile.getStatus() == MyFile.FILE_STATUS_REMOTE) {
                remoteFileCount++;
            } else if (myFile.getStatus() == MyFile.FILE_STATUS_UPLOAD_SUCCESS) {
                uploadSuccessCount++;
            }
        }
        //如果上传全部失败，又没有选择远程文件，那么此次发布topic宣告失败
        if (remoteFileCount == 0 && uploadSuccessCount == 0) {

            mHandler.post(() -> {
                listener.onShowToast("上传文件失败，请稍后重试");
                listener.onHideProgressBar();
            });
            return;
        }
        mHandler.post(() -> {
            listener.onUploadComplete();
            listener = null;
        });

    }


    public interface InteractionListener {
        void onShowToast(String content);

        void onShowProgressBar(String content);

        void onHideProgressBar();

        void onUploadComplete();
    }
}
